const urlParams = new URLSearchParams(new URL(window.location.href).search);
let id = urlParams.get('id');
let states = urlParams.get('state');
$().ready(function() {
	validateRule();
	ifState()
	radioChange()
	imageCreate()
	inputChange()
	radiosListChange()
});


// 页面判断区分管理员和教师
function ifState() {
	let state = $('#authority').val()
	if(state === '管理员') {
		$('.Administrator').show()
		$('.teacher').hide()
	}else {
		$('.teacher').show()
		$('.Administrator').hide()
	}
}

$.validator.setDefaults({
	submitHandler : function() {
		save();
	}
});

//参数初始表单回填
async function radiosListChange() {
	//判断是否编辑还是详情
	if(states === '0') {
		$('#submitBtns').show()
		$('#btnUpload').show()
	}else {
		$('input[type="text"], textarea, select').prop('readonly', true);
		$('select').prop('disabled', true);
		$('.stateZy').hide()
		$('.stateZyk').hide()
		$('#submitBtns').hide()
		$('#btnUpload').hide()
	}

	let {data} = await submitFrom()
	$('#signupForm input[name="name"]').val(data.name);
	$('#signupForm input[name="couName"]').val(data.couName);
	$('#signupForm textarea[name="couIntroduce"]').val(data.couIntroduce);
	$('#signupForm input[name="sort"]').val(data.sort);
	$('#selectChange').val(data.newType)
	$('#imgFil').attr('src',data.introducePortrait)
	$('#newType').val(data.newType)

	switch (data.publicity) {
		case '0':
			$('input[name="publicity"][value="0"]').prop('checked', true);
			$('#selectChange').show()
			break;
		case '1':
			$('input[name="publicity"][value="1"]').prop('checked', true);
			$('#selectChange').hide()
			break;
		default:
			break;
	}
	switch (data.state) {
		case '0':
			$('input[name="state"][value="0"]').prop('checked', true);
			$('#selectChanges').show()
			break;
		case '1':
			$('input[name="state"][value="1"]').prop('checked', true);
			$('#selectChanges').hide()
			break;
		default:
			break;
	}
}

// 输入框事件
function inputChange() {
	$('#sort').blur(function() {
		let value = $(this).val();
		let data = {
			sort: ''
		}
		data.sort = value
		if(value !== ''){
			inputFrom(data)
		}

	});
}

// 图片处理
function imageCreate(){
	$('#imgFil').click(function (){
		var imageUrl = $(this).attr('src');
		$('.overlay').toggleClass('active');
		$('.overlay img').attr('src', imageUrl);
	})
	$('.overlay').click(function() {
		$(this).removeClass('active');
	});

}


// 页面判断
function radioChange() {
	let radios = document.getElementsByName('publicity');
	let radiosAll = document.getElementsByName('state');
	for (let i = 0; i < radios.length; i++) {
		radios[i].addEventListener('change', function() {
			if(this.value === '0') {
				$('#selectChange').show()
			}else {
				$('#selectChange').hide()
			}
		});
	}
	for (let i = 0; i < radiosAll.length; i++) {
		radiosAll[i].addEventListener('change', function() {
			console.log(this.value)
			if(this.value === '0') {
				$('#selectChanges').show()
			}else {
				$('#selectChanges').hide()
			}
		});
	}
}

// 修改
function save() {
	let imgs = $('#imgAll').children().length
	if(imgs === 0) {
		layer.msg("请上传资源封面")
		return
	}
	let img = $('#imgFil').attr('src')
	let formData = $('#signupForm').serializeArray();
	let  data = {};
	$.each(formData, function(index, item) {
		data[item.name] = item.value;
	});
	data['introducePortrait'] = img
	data['id'] = id
	addFrom(data)

}
function validateRule() {
	var icon = "<i class='fa fa-times-circle'></i> ";
	$("#signupForm").validate({
		rules : {
			name:{
				required : true
			},
			couName : {
				required : true
			},
			couIntroduce : {
				required : true
			},
			title : {
				required : true
			},
			content : {
				required : true
			}
		}
	})
}

// 上传
 layui.use('upload', function () {
        var upload = layui.upload;
        //执行实例
        upload.render({
            elem: '#btnUpload', //绑定元素
            url: 'http://10.3.0.64:9900/minio/uploadFile', //上传接口
            accept: 'file',
            done: function (r) {
				$('#imgAll').html(`<img src="${r.data}" id="imgFil" style="max-width: 50%;height: auto;cursor: pointer;" />`)
            },
            error: function (r) {
                layer.msg(r.msg);
            }
        });
    });

// 修改资源接口
function addFrom(data) {
	return new Promise(function (resolve, reject) {
		$.ajax({
			url: '/courses/update',
			type: 'POST',
			contentType: 'application/json',
			data: JSON.stringify(data),
			success: function(response) {
				// 请求成功时的处理
				if(response.code !== '0') {
					layer.msg(response.msg);
				}else {
					let index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
					parent.layer.close(index);
					parent.reLoad();
					resolve(response)
				}

			},
			error: function(xhr, status, error) {
				// 请求失败时的处理
				layer.msg(error);
				reject(error)
			}
		});
	})

}


//查询资源
function submitFrom() {
	return new Promise(function (resolve, reject) {
		$.ajax({
			type: 'get',
			url: `/courses/getCourseById?id=${id}`,
			success: function(data) {
				if(data.code != '0'){
					layer.msg(data.msg)
					reject(data.code)
					return
				}
				resolve(data)
			},
			error: function(xhr, textStatus, error) {
				reject(data.code)
			}
		});
	})

}

//优先级接口
function inputFrom(data) {
	return new Promise(function (resolve, reject) {
		$.ajax({
			url: '/courses/effect',
			type: 'POST',
			contentType: 'application/json',
			data: JSON.stringify(data),
			success: function(response) {
				// 请求成功时的处理
				if(response.code !== '0') {
					layer.msg(response.msg);
					$('#sort').val('')
					return
				}
			},
			error: function(xhr, status, error) {
				// 请求失败时的处理
				layer.msg(error);
				resolve(error)
			}
		});
	})
}
function limitTextarea(element, maxLength) {
	if (element.value.length > maxLength) {
		element.value = element.value.slice(0, maxLength);
		layer.msg('文字超出限制');
	}
}